package com.zmz.juc.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

//阻塞队列
public class BlockingQueueDemo {

    public static void main(String[] args) throws InterruptedException {
        //offer() 方法：当尝试将元素添加到队列时，如果队列已满，它会返回 false，表示添加失败，但不会抛出异常。
        //add() 方法：当尝试将元素添加到队列时，如果队列已满，它会抛出 IllegalStateException 异常。
        //如果队列没有空间可用（即队列已满），调用 put() 方法的线程将被阻塞，一直等到队列有足够的空间来容纳元素。
        //创建阻塞队列
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
        BlockingQueue<String> secondQueue = new ArrayBlockingQueue<>(3);
        try {
            //第一组
            System.out.println("第一组-----------------");
            System.out.println(blockingQueue.add("a"));
            System.out.println(blockingQueue.add("b"));
            System.out.println(blockingQueue.add("c"));
            System.out.println(blockingQueue.element()); //获取队列头部元素但不会剔除该元素

            System.out.println(blockingQueue.add("w"));
            System.out.println(blockingQueue.remove());
            System.out.println(blockingQueue.remove());
            System.out.println(blockingQueue.remove());
            System.out.println(blockingQueue.remove());
        }catch (Exception e){
            System.out.println("第一组异常:"+e.toString());
        }
        //第二组
        System.out.println("第二组-----------------");
        System.out.println(secondQueue.offer("a"));
        System.out.println(secondQueue.offer("b"));
        System.out.println(secondQueue.offer("c"));
        System.out.println(secondQueue.offer("www"));

        System.out.println(secondQueue.poll());
        System.out.println(secondQueue.poll());
        System.out.println(secondQueue.poll());
        System.out.println(secondQueue.poll());

        //第三组
        System.out.println("第三组-----------------");
        secondQueue.put("a");
        secondQueue.put("b");
        secondQueue.put("c");
//        secondQueue.put("w");// put满了发生阻塞
        System.out.println(secondQueue.take());
        System.out.println(secondQueue.take());
        System.out.println(secondQueue.take());
//        System.out.println(secondQueue.take());

        //第四组
        System.out.println("第四组-----------------");
        System.out.println(secondQueue.offer("a"));
        System.out.println(secondQueue.offer("b"));
        System.out.println(secondQueue.offer("c"));
        System.out.println(secondQueue.offer("w",3L, TimeUnit.SECONDS));
    }
}
